<template>
  <div class="app-container">
    <div class="head">
      <img src="@/assets/img/Layout/position.png" />
      <p class="see-block">唯一标识</p>
    </div>
    <div class="view-container">
      <el-row class="status-title">
        <el-col class="mr20 width100">
            <el-button
                class="btn-success width100"
                type="primary"
                @click="getPalletCode"
            >生成大码</el-button>
        </el-col>
        <el-col class="mr20 width100">
            <el-button
                class="btn-success width100"
                type="primary"
                @click="getMotherCode"
            >生成母码</el-button>
        </el-col>
        <el-col class="mr20 width100">
            <el-button
                class="btn-success width100"
                type="primary"
                @click="getSubCode"
            >生成子码</el-button>
        </el-col>
      </el-row>
      <p class="mtb10">可下载数量：{{ data.downloadQuantity }}<span style="margin-left: 20px;">已下载数量：</span>{{ data.generatedQuantity }}</p>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="mt30">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品属性:" prop="productProperties" class="icon-star">
              <el-select v-model="form.productProperties" placeholder="请选择" style="width:100%;" @change="onProductProperties">
                <el-option label="采购" value="1">采购</el-option>
                <el-option label="自产" value="2">自产</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品名称:" prop="productBasicName" v-if="form.productProperties=='2'">
              <el-input v-model="form.productBasicName " placeholder="请选择产品" @focus="productShow" clearable @clear="productClear" ref="getFocus" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="大码标识:" prop="largeSizeIdentification">
              <el-input v-model="form.largeSizeIdentification" placeholder="" :disabled="form.productProperties=='2'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="箱码标识:" prop="productIdentification">
              <el-input v-model="form.boxCodeIdentification" placeholder="" :disabled="form.productProperties=='2'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品标识:" prop="productIdentification">
              <el-input v-model="form.productIdentification" placeholder="" :disabled="form.productProperties=='2'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="码格式:" prop="codeFormat">
              {{ form.codeFormat == '1' ? '一物一码' : form.codeFormat == '2' ? 'UDI码' : '' }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产日期:" prop="productionDate">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.productionDate" suffix-icon="el-icon-date" type="date" placeholder="请选择生产日期" style="width:100%;" @change="onChangeProductionDate">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="生产批号:" prop="batchNumber">
              <el-input v-model="form.batchNumber" placeholder="" :disabled="form.productProperties=='2'" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
             <el-form-item label="生成码数量:" prop="number">
              <el-input v-model.number="form.number" placeholder="请输入生成码数量" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="失效日期:" prop="expirationDate">
              <el-date-picker value-format="yyyy-MM-dd" v-model="form.expirationDate" suffix-icon="el-icon-date" type="date" placeholder="请选择失效日期" style="width:100%;" @change="onChangeExpirationDate">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!-- 弹出数据 -->
    <el-dialog title="生产计划" :visible.sync="open" width="70%" top="50px" append-to-body center :before-close="handleClose">
      <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入名称或编码检索"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="dataList" @row-click="onSelectData" :default-sort="{prop: 'date', order: 'descending'}" border>
        <el-table-column label="序号" type="index" align="center" width="50">
           <template slot-scope="scope">
            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column label="计划编码" align="center" prop="planCode" />
        <el-table-column label="产品名称" align="center" prop="productBasicName" />
        <el-table-column label="规格名称" align="center" prop="productName" />
        <el-table-column label="产品批号" align="center" prop="batchNumber" />
        <el-table-column label="码格式" align="center" prop="codeFormat">
          <template slot-scope="scope">
            <div v-if="scope.row.codeFormat == 1">一物一码</div>
            <div v-if="scope.row.codeFormat == 2">UDI码</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="productStatus">
          <template slot-scope="scope">
            <div v-if="scope.row.plunStatus == 0" style="color:#52C41A">计划中</div>
            <div v-if="scope.row.plunStatus == 1" style="color:#52C41A">进行中</div>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="approveStatus">
          <template slot-scope="scope">
            <div v-if="scope.row.approveStatus == 1" style="color:#52C41A">已审核</div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getProduct"
      />
    </el-dialog>
  </div>
</template>

<script>
import { motherCode, subCode, listProduct, numberCode, codeLimit, palletCode } from  "@/api/system/quickcode/udicode"
import { udiPlanList } from "@/api/system/plan/plan"
export default {
  name: "udiCode",
  data() {
    var checkAge = (rule, value, callback) => {
      // if (value == '') {
      //   return callback(new Error('生成码数量不能为空'))
      // }else
      if(value == 0){
        return callback(new Error('生成码数量必须大于0'))
      }
      if (!Number.isInteger(value)) {
        callback(new Error('请输入数字值'))
      } else {
        callback()
      }
    }
    return {
      form: {
        productProperties:'2',
        productBasicName: '', // 产品名称
        productIdentification: '', // 产品标识
        boxCodeIdentification: '', // 箱码标识
        largeSizeIdentification: '', // 大码标识
        productionDate: '', // 生产日期
        batchNumber: '', // 生产批号
        number: '', // 生成码数量
        expirationDate: '', // 失效日期
        codeFormat: ''
      },
      // 表单校验
      rules: {
        productBasicName: [
          { required: true, message: "产品名称不能为空",}
        ],
        // productIdentification: [
        //   { required: true, message: "产品标识不能为空"}
        // ],
        productionDate: [
          { required: true, message: "生产日期不能为空", trigger: "blur" }
        ],
        batchNumber: [
          { required: true, message: "生产批号不能为空", trigger: "blur" }
        ],
        number: [
          { required: true, validator: checkAge, trigger: "blur" }
        ],
        expirationDate: [
          { required: true, message: "失效日期不能为空", trigger: "blur" }
        ],
      },
      open: false,
      loading: true,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: undefined,
        // plunStatus: 0,
        // approveStatus: 1
      },
      // 弹出数据列表
      dataList: [],
      data: ''
    };
  },
  created() {
    this.getCodeLimit()
  },
  methods: {
    onChangeProductionDate(e){
      var date = new Date(e)
      this.productionDate = date.getTime()
      if(this.expirationDate == undefined || this.expirationDate == ''){
        // console.log('111')
      }else{
        if(this.productionDate >= this.expirationDate){
          this.form.productionDate = ''
          this.productionDate = ''
          this.$modal.msgError('生产日期不能大于失效日期！')
        }
      }
    },
    onChangeExpirationDate(e){
      var date = new Date(e)
      this.expirationDate = date.getTime()
      if(this.productionDate > 0){
        if(this.expirationDate <= this.productionDate){
          this.form.expirationDate = ''
          this.expirationDate = ''
          this.$modal.msgError('失效日期必须大于生产日期！')
        }
      }else{
        this.form.expirationDate = ''
        this.expirationDate = ''
        this.$modal.msgError('生产日期不能为空！')
      }
    },
    // 码数量
    getCodeLimit(){
      codeLimit().then(res => {
        this.data = res.data
      })
    },
    // 产品弹窗显示
    productShow(){
      this.open = true
      this.getProduct()
    },
    //请求产品列表
    getProduct(){
      this.loading = true
      udiPlanList(this.addDateRange(this.queryParams)).then(res => {
        this.dataList = res.rows
        this.total = res.total
        this.loading = false
      })
    },
    // 删除产品
    productClear(){
      this.form.productBasicName = ''
      this.form.productionDate = ''
      this.form.batchNumber = ''
      this.form.productIdentification = ''
      this.form.boxCodeIdentification = ''
      this.form.largeSizeIdentification = ''
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getProduct()
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 选中产品
    onSelectData(row){
      this.form.codeFormat = row.codeFormat
      listProduct({ productId: row.productId }).then(res => {
        this.form.productIdentification = res.data.productIdentification
        this.form.boxCodeIdentification = res.data.boxCodeIdentification
        this.form.largeSizeIdentification = res.data.largeSizeIdentification
        // this.form.productionDate = row.planStartTime.split(' ')[0]
        this.form.batchNumber = row.batchNumber
        this.form.productBasicName = row.productBasicName
        this.open = false
        this.queryParams.productName = ''
      })
    },
    // 关闭弹窗
    handleClose(){
      this.open = false
      this.queryParams.productName = undefined
    },
    // 产品属性切换
    onProductProperties(e){
      this.form = {}
      this.form.productProperties = e
    },
    // 下载大码
    getPalletCode(){
      this.$refs["form"].validate(v => {
        if(v){
          if(this.form.largeSizeIdentification !== '' && this.form.largeSizeIdentification !== null){
            numberCode(this.form.number).then(res => {
              if(res.data == '0'){
                this.$modal.loading("正在下载")
                const { productBasicName, ...result } = this.form
                palletCode(result).then((response)=>{
                  this.$modal.closeLoading()
                  this.form.number = ''
                  let str = new Blob([response], {type: 'text/plain;charset=utf-8'})
                  saveAs(str, `大码.txt`)
                  // let str = new Blob([response], {type: 'application/zip'})
                  // saveAs(str, `子码.zip`)
                })
              }else{
                this.$modal.msgError('生成码数量超过限制，请联系管理员!')
              }
            })
          }else{
            this.$modal.msgError('大码标识不能为空！')
          }
        }
      })
    },
    // 下载母码
    getMotherCode(){
      this.$refs["form"].validate(v => {
        if(v){
          numberCode(this.form.number).then(res => {
            if(res.data == '0'){
              this.$modal.loading("正在下载")
              const { productBasicName, ...result } = this.form
              // console.log(result)
              motherCode(result).then((response)=>{
                this.$modal.closeLoading()
                this.form.number = ''
                let str = new Blob([response], {type: 'text/plain;charset=utf-8'})
                saveAs(str, `母码.txt`)
              })
            }else{
              this.$modal.msgError('生成码数量超过限制，请联系管理员!')
            }
          })
        }
      })
    },
    // 下载子码
    getSubCode(){
      this.$refs["form"].validate(v => {
        if(v){
          numberCode(this.form.number).then(res => {
            if(res.data == '0'){
              this.$modal.loading("正在下载")
              const { productBasicName, ...result } = this.form
              subCode(result).then((response)=>{
                this.$modal.closeLoading()
                this.form.number = ''
                let str = new Blob([response], {type: 'text/plain;charset=utf-8'})
                saveAs(str, `子码.txt`)
                // let str = new Blob([response], {type: 'application/zip'})
                // saveAs(str, `子码.zip`)
              })
            }else{
              this.$modal.msgError('生成码数量超过限制，请联系管理员!')
            }
          })
        }
      })
    }
  }
}
</script>
